/**
 * Copyright (C) 2018 - 2020 https://github.com/LeeYan9
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.task;

import com.bifrost.constant.BonusPointsSource;
import com.bifrost.constant.BonusPointsUpdatedDetail;
import com.bifrost.entity.Customer;
import com.bifrost.entity.ExtMemberBonusPoints;
import com.bifrost.repository.CustomerRepository;
import com.bifrost.repository.ExtMemberBonusPointsRepository;
import com.bifrost.service.BonusPointsService;
import com.bifrost.service.CustomerService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.aop.framework.AopContext;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.List;

/**
 * @author Lee
 * Create Class on 2018/11/29
 * @com.bifrost.task
 * @wechat-mall
 */
@Component
@JobHandler("importedExtBonusPoints")
public class ImportedExtBonusPoints extends IJobHandler{

    @Autowired
    ExtMemberBonusPointsRepository extRepository;
    @Autowired
    CustomerRepository customerRepository;
    @Autowired
    BonusPointsService bonusPointsService;


    @Override
    public ReturnT<String> execute(String s) throws Exception {
        XxlJobLogger.log("开始执行定时导入外部积分功能.");
        List<ExtMemberBonusPoints> extMemberBonusPoints = extRepository.findAll();
        if(extMemberBonusPoints.isEmpty()){
            return new ReturnT<>("没有需要导入积分的外部会员数据");
        }
        extMemberBonusPoints.forEach(ext -> {
            List<Customer> customers = customerRepository.findByStoreIdAndPhone(ext.getMerchantId(), ext.getPhone());
            if(customers.isEmpty()) {
                return;
            }
            try {
                ((ImportedExtBonusPoints)AopContext.currentProxy()).importedPonits(ext, customers.get(0));
            } catch (Exception e) {
                XxlJobLogger.log(e);
            }
        });
        XxlJobLogger.log("执行定时导入外部积分功能结束");
        return ReturnT.SUCCESS;
    }


    @Transactional(rollbackFor = Exception.class)
    public void importedPonits(ExtMemberBonusPoints ext, Customer customer) {
        BigInteger addPoints = ext.getBonusPoints()==null?BigInteger.ZERO:ext.getBonusPoints();
        String remark = String.format("用户重新绑定会员，完成外部积分导入：会员ID:%s , 增加积分：%s", customer.getCustomerId(), addPoints);
        bonusPointsService.incrementBonusPoints(customer, null, addPoints, BonusPointsSource.OTHER, BonusPointsUpdatedDetail.BY_ADMINUSER,remark);
        extRepository.delete(ext);
        XxlJobLogger.log(remark);
    }

}